﻿using System;
using System.Data;
using System.Reflection;
using System.Text;

namespace MyORM.core
{
    class ObjectUtils
    {
        internal static object copyValue(object t, DataRow dr)
        {
            PropertyInfo[] fields = t.GetType().GetProperties();
            if (fields.Length > 0)
            {
                DataColumnCollection columns = dr.Table.Columns;
                string colName;
                object obj;
                foreach (PropertyInfo field in fields)
                {
                    colName = transferName(field.Name);
                    if (columns.Contains(colName))
                    {
                        obj = dr[colName];
                        if (!(obj is DBNull))
                        {
                            if (obj.GetType() == typeof(DateTime) && field.PropertyType == typeof(string))
                                field.SetValue(t, Convert.ToDateTime(dr[colName]).ToString("yyyy-MM-dd HH:mm:ss"), null);
                            else
                                field.SetValue(t, dr[colName], null);
                        }
                    }
                }
            }
            return t;
        }

        private static string transferName(string p)
        {
            char[] array = p.ToCharArray();
            StringBuilder sb = new StringBuilder();
            foreach (char c in array)
            {
                if (c >= 'A' && c <= 'Z')
                    sb.Append("_").Append(c.ToString().ToLower());
                else
                    sb.Append(c.ToString().ToLower());
            }
            return sb.ToString().Trim('_');
        }
    }
}
